package com.xpfirst.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.xpfirst.ActivityManage;

import android.os.Bundle;
import android.os.Message;
import android.util.Log;

public class SocketClient implements Runnable{
	public Socket socket=null;
	public void init(String host,int port){
		try{
			socket=new Socket(host,port);
			Log.v("client socket", "connected");
			
		} catch (UnknownHostException e) {
			SocketManage.close();
		} catch (IOException e) {
			SocketManage.close();
		}catch(Exception e){
			SocketManage.close();
		}
	}
	public void write(String str){
		try{
			if( (socket != null) && socket.isConnected()){
				PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
				out.println(str);
				Log.e("get data from",str);
			}

		}catch(Exception e){
			SocketManage.close();
		}
	}
	public void close(){
		if(socket != null){
			try{
				socket.close();
			}catch(IOException e){
				Log.v("IOException", e.getMessage());
			}
			socket = null;
		}
	}
	public void run() {
		while(true){
			if((socket != null)){
				if(socket.isConnected()){
					try{
						BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
						String mstr=br.readLine();
						if(mstr != null){
					        ActivityManage.sendMsg(0, "socket", mstr);
						}
					}
					catch(Exception ex){
						SocketManage.close();
					}
				}
			}
		}
	}
}
